package controler;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JList;
import javax.swing.JRadioButton;

import java.util.Observable;

import template.AbstractListener;

import model.BooleanModel;
import model.Delivery;

public class RemoveListener extends AbstractListener implements ActionListener{
	
	private static final long serialVersionUID = 1L;
	private JList facturePreview;
	
	public RemoveListener(Observable obs1, Observable obs2, Observable obs3, JList l){
		addModel(obs1);
		addModel(obs2);
		addModel(obs3);
		facturePreview = l;
	}
	
	@Override
	public void actionPerformed(ActionEvent evt){
		Delivery model = (Delivery)getModel(0);
		BooleanModel boolModelRestaurantChooser = (BooleanModel)getModel(1);
		BooleanModel boolModelButton = (BooleanModel)getModel(2);
		
		if(model.getDeliveryElements().size() == 1){
			boolModelRestaurantChooser.setValue(true);
			boolModelButton.setValue(false);
		}
		
		if(model.getDeliveryElements().size() > 0){
			model.removeDeliveryElement((int)getSelection());
		}
	}
	
	private Integer getSelection(){
		Object[] choosers = (Object[])facturePreview.getComponents();
		Integer selectedValue = null;
		
		for(int i = 0; i < choosers.length; i+=2){
			JRadioButton radioBt = (JRadioButton)choosers[i];
			
			if(radioBt.isSelected()){
				selectedValue = Integer.parseInt(radioBt.getName());
				break;
			}
		}
		
		return selectedValue;
	}
	
}
